package com.lastcrdg.textcustomview.CustomView;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

/**
 * author：liluo
 * e-mail：lastcrazysun@163.com
 * company：cusc
 * date：2017/9/20 13:55
 * description：
 */

public class CircleView extends View {

    private RectF mRectF = new RectF(400, 400, 600, 600);
    private float angel = 0;
    private Handler mHandler = new Handler();

    public CircleView(Context context) {
        this(context, null);
    }

    public CircleView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        Paint colorPaint = new Paint();
        colorPaint.setTextSize(48);
        colorPaint.setColor(Color.BLACK);
        colorPaint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.GRAY);
        //抗锯齿
        paint.setAntiAlias(true);
        paint.setStrokeWidth(20);
        paint.setStyle(Paint.Style.STROKE);
        canvas.drawArc(mRectF, 0, 360, false, paint);
        paint.setColor(Color.RED);
        if (angel < 360) {
            angel++;
            canvas.drawArc(mRectF, 0, angel, false, paint);
            canvas.drawText(((int) angel * 100 / 360) + "%", 476, 524, colorPaint);
            mListener.currentPercent((int) angel * 100 / 360);
            drawCirle();
        } else {
            canvas.drawArc(mRectF, 0, angel, false, paint);
            canvas.drawText(((int) angel * 100 / 360) + "%", 476, 524, colorPaint);
            mListener.currentPercent((int) angel * 100 / 360);
        }
    }

    private void drawCirle() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (angel < 361) {
                    postInvalidate();
                }
            }
        }, 10);
    }

    public interface OnPercentListener {
        void currentPercent(int percent);
    }

    private OnPercentListener mListener;

    public void setOnPercentListener(OnPercentListener listener) {
        mListener = listener;
    }
}
